package com.sqx.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.*;
import com.sqx.modules.app.entity.*;
import com.sqx.modules.app.service.*;

import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.goods.service.GoodsService;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.AliPayService;
import com.sqx.modules.pay.service.WxService;

import com.sqx.modules.stockManage.dao.StockManageDao;
import com.sqx.modules.stockManage.entity.StockManage;
import com.sqx.modules.stockManage.service.impl.StockManageServiceImpl;
import com.sqx.modules.tbOrders.dao.TbOrdersDao;
import com.sqx.modules.tbOrders.entity.TbOrders;
import com.sqx.modules.tbOrders.service.TbOrdersService;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Service
@Slf4j
public class UserMoneyServiceImpl extends ServiceImpl<UserMoneyDao, UserMoney> implements UserMoneyService {
    @Autowired
    private UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    private WxService wxService;
    @Autowired
    private AliPayService aliPayService;
    @Autowired
    private TbOrdersService tbOrdersService;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private CommonInfoService commonInfoService;

    @Autowired
    private UserService userService;
    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private StockManageDao stockManageDao;

    @Override
    public void updateMoney(int i, Long userId, double money) {
        baseMapper.updateMayMoney(i, userId, money);
    }

    @Override
    public UserMoney selectUserMoneyByUserId(Long userId) {
        return baseMapper.selectOne(new QueryWrapper<UserMoney>().eq("user_id", userId));
    }

    @Override
    public Double selectMyProfit(Long userId) {

        return userMoneyDetailsDao.selectMyProfit(userId);
    }


    @Override
    public IPage<UserMoneyDetails> balanceDetailed(Long page, Long limit, UserMoneyDetails userMoneyDetails) {
        Page<UserMoneyDetails> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
        }
        return userMoneyDetailsDao.selectPage(pages, new QueryWrapper<>(userMoneyDetails).orderByDesc("create_time"));
    }

    @Override
    public Result rechargeMoney(Long userId, BigDecimal money, Integer classify) throws Exception {
        if (classify == 1 || classify == 2 || classify == 3) {
            //微信
            return wxService.payMoney(userId, money, null, classify);
        } else if (classify == 4 || classify == 5) {
            //支付宝支付
            return aliPayService.payMoney(userId, money, null, classify);
        } else {
            return Result.error("支付方式错误!");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result moneyPayIndent(Long userId, Long orderId) {
        TbOrders order = tbOrdersService.getById(orderId);
        if (order != null) {
            Goods goods = goodsDao.selectById(order.getGoodId());
            if (goods == null) {
                return Result.error("该商品不存在");
            }
            Integer count = goodsDao.countByGoodId(goods.getGoodId());
            if (count > 0) {
                return Result.error("该商品已被买走或售罄，请选择其他商品");
            }
            if (goods.getIsEnable() != 1 || goods.getStatus() != 1) {
                return Result.error("该商品已下架或状态异常，请刷新后重试！");
            }
            if (order.getStatus() == 0) {
//                UserMoney userMoney = userMoneyDao.selectOne(new QueryWrapper<UserMoney>().eq("user_id", userId));
                UserEntity userEntity = userDao.selectById(userId);
                if (userEntity != null && userEntity.getBalance().compareTo(order.getTotalPrice()) >= 0) {
                    userEntity.setBalance(userEntity.getBalance().subtract(order.getTotalPrice()));
                    if (userEntity.getCreditScore() < 100) {
                        userEntity.setCreditScore(userEntity.getCreditScore() + 1);
                    }
                    userDao.updateById(userEntity);
                    if (order.getDeliveryStatus() == 0 || order.getDeliveryStatus() == 1) {
                        order.setStatus(1);
                    } else {
                        order.setStatus(2);
                    }
                    order.setIsPay(1);
                    order.setPayWay(6);
                    order.setPayTime(new Date());
                    tbOrdersService.updateById(order);
                    UserEntity userEntity1 = userService.selectUserById(order.getBuyerId());
                    if (userEntity1 != null) {
                        MessageInfo messageInfo = new MessageInfo();
                        messageInfo.setUserId(String.valueOf(userEntity1.getUserId()));
                        messageInfo.setTitle("下单成功通知，订单号：" + order.getOrderNumber());
                        messageInfo.setContent("您已下单成功");
                        messageInfo.setCreateAt(DateUtils.format(new Date()));
                        messageInfo.setIsSee("0");
                        messageInfo.setStatus(0);
                        messageInfo.setState(String.valueOf(6));
                        messageInfo.setUserName(userEntity1.getUserName());
                        messageInfoDao.insert(messageInfo);
                    }
                    UserEntity user = userService.selectUserById(order.getSellerId());
                    MessageInfo messageInfos = new MessageInfo();
                    messageInfos.setUserId(String.valueOf(user.getUserId()));
                    messageInfos.setTitle("您的商品已被成功购买通知，订单号：" + order.getOrderNumber());
                    messageInfos.setContent("您商品已被成功购买");
                    messageInfos.setCreateAt(DateUtils.format(new Date()));
                    messageInfos.setIsSee("0");
                    messageInfos.setStatus(0);
                    messageInfos.setState(String.valueOf(6));
                    messageInfos.setUserName(user.getUserName());
                    messageInfoDao.insert(messageInfos);
                    if (goods.getStockId() != null) {
                        StockManage stockManage = stockManageDao.selectById(goods.getStockId());
                        if (stockManage != null) {
                            stockManage.setStock(stockManage.getStock() - order.getBuyNum());
                            stockManage.setOutStock(stockManage.getOutStock() + order.getBuyNum());
                            stockManageDao.updateById(stockManage);
                            if (goods.getStock() == 0) {
                                goods.setStatus(1);
                                goods.setIsEnable(0);
                                goodsDao.updateById(goods);
                            }
                        }
                    } else if (goods.getIsStock() != null) {
                        if (goods.getIsStock() == 2 && goods.getStock() == 0) {
                            goods.setStatus(1);
                            goods.setIsEnable(0);
                            goodsDao.updateById(goods);
                        } else if (goods.getIsStock() == 2 && goods.getStock() > 0) {
                            goods.setStatus(1);
                            goods.setIsEnable(1);
                            goods.setStock(goods.getStock() - order.getBuyNum());
                            goodsDao.updateById(goods);
                        } else if (goods.getIsStock() == 1) {
                            goods.setStatus(1);
                            goods.setIsEnable(0);
                            goodsDao.updateById(goods);
                        }
                    } else {
                        goods.setStatus(1);
                        goods.setIsEnable(0);
                        goodsDao.updateById(goods);
                    }
//                        goods.setIsEnable(0);
//                        goodsDao.updateById(goods);
                    PayDetails payDetails = payDetailsDao.selectOne(new QueryWrapper<PayDetails>().eq("order_id", order.getOrderNumber()));
                    if (payDetails == null) {
                        payDetails = new PayDetails();
                        payDetails.setState(1);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        payDetails.setCreateTime(sdf.format(new Date()));
                        payDetails.setOrderId(order.getOrderNumber());
                        payDetails.setUserId(userId);
                        payDetails.setMoney(order.getTotalPrice().doubleValue());
                        payDetails.setClassify(6);
                        payDetails.setType(2);
                        payDetailsDao.insert(payDetails);
                    } else {
                        payDetails.setState(1);
                        payDetails.setClassify(6);
                        payDetailsDao.updateById(payDetails);
                    }
                    UserEntity userByWxId = userDao.selectById(order.getSellerId());
                    String value = commonInfoService.findOne(79).getValue();
                    String value1 = commonInfoService.findOne(86).getValue();
                    if ("1".equals(value) || "3".equals(value)) {
                        Result result = userService.sendMsg(userByWxId.getPhone(), "2");
                        if (result.get("code").equals(0) || !result.get("code").equals(0)) {
                            log.warn("发送短信");
                        }
                    } else {
                        Result result = userService.sendMsgAlibabaByValue(userByWxId.getPhone(), null, value1);
                        if (result.get("code").equals(0) || !result.get("code").equals(0)) {
                            log.warn("发送短信");
                        }
                    }
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(userId);
                    userMoneyDetails.setMoney(order.getTotalPrice());
                    userMoneyDetails.setContent("零钱支付：" + order.getTotalPrice());
                    userMoneyDetails.setTitle("支付成功");
                    userMoneyDetails.setType(2);
                    userMoneyDetails.setClassify(1);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format = simpleDateFormat.format(new Date());
                    userMoneyDetails.setCreateTime(format);
                    userMoneyDetailsDao.insert(userMoneyDetails);
                    return Result.success();
                } else {
                    return Result.error("余额不足，请充值");
                }
//                if (userMoney.getMoney().compareTo(order.getTotalPrice()) >= 0) {
//                    userMoneyDao.updateMayMoney(2, order.getBuyerId(), order.getTotalPrice().doubleValue());
//                    order.setIsPay(1);
//                    order.setPayWay(6);
//                    order.setPayTime(new Date());
//                    tbOrdersService.updateById(order);
//                    tbOrdersService.setCommission(order.getOrderId(), 1);
//                    return Result.success();
//                } else {
//                    return Result.error("余额不足，请充值");
//                }
            } else {
                return Result.error("该订单状态已变更，请刷新");
            }
        }
        return Result.error("该订单不存在");
    }


}
